from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
import json
from application.models.users.user import *
from application.models.users.user import db
from utils.Myjwt import myjwt
import functools,time
import requests
# from db import db
wb_blue=Blueprint("wblogin",__name__)
api=Api(wb_blue)

# 三方登录
@wb_blue.route("/getWburl")
def getWburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (client_id, redirect_uri)
    return jsonify({"code": 200, "url": url})

# 微博回调接口
@wb_blue.route("/weiboCallback/")
def weiboCallback():
    # 获取code
    code=request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message=json.loads(res.text)
    print(message)
    token=message["access_token"]
    print(token)
    uid=message["uid"]
    # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
    # sf=SfLogin.query.filter(SfLogin.uid==uid).first()
    # if sf:
    #     for i in sf:
    #         user=User.query.filter(User.id==sf.userid).first()
    #         data={"data":{"userid":i[0],"exp":int(time.time())}}
    #         token=myjwt.jwt_encode(data)
    #         return redirect("http://localhost:8080/#/updateToken?token=" + token + "&userid=" + str(i[0]))
    sql="select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid))
    user=db.session.execute(sql)
    if user:
        # 生成jwt 返回jwt token
        for i in user:
            data={"data":{"userid":i[0],"exp":int(time.time())}}
            token =myjwt.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?token="+str(token)+"&userid="+str(i[0]))
    # 绑定
    return redirect("http://localhost:8080/#/webbd?token="+str(token)+"&uid="+str(uid))

# 绑定
@wb_blue.route("/bindM",methods=["POST"])
def bindM():
    # 接收参数
    data=json.loads(request.data)
    mobile=data["mobile"]
    uid=data["uid"]
    token=data["token"]
    # 加入用户表
    user=User.query.filter(User.mobile==mobile).first()
    if not user:
        # 添加
        u=User(mobile=mobile,nikename=mobile)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user=User.query.filter(User.mobile==mobile).first()
    sfuser=SfLogin(userid=user.id,webfrom="wb",uid=uid,token=token)
    print("sss",sfuser)
    db.session.add(sfuser)
    db.session.commit()
    data={"data":user.id,"exp":int(time.time())}
    token=myjwt.jwt_encode(data)
    return redirect("http://localhost:8080/#/updateToken?token=" + token + "&userid=" + str(user.id))